<script setup>
import { reactive } from 'vue';
import { useRouter } from 'vue-router';
import axios from 'axios';

import {
  ElContainer,
  ElHeader,
  ElMain,
  ElFooter,
  ElTabs,
  ElTabPane,
  ElForm,
  ElFormItem,
  ElInput,
  ElButton,
  ElMessage
} from 'element-plus';

const form = reactive({
  email: '',
  tel: '',
  password: ''
});

const router = useRouter();

function login() {
  const entity = { ...form }
  axios.post('/backapi/customer/login', entity)
       .then( resp => {
        const { success, message, token } = resp.data;
        if( success ){
          // 将 token 保存到 
          sessionStorage.setItem( 'token', token ); // 当前会话有效
          // localStorage.setItem( 'token', token ); // 浏览器清除本地存储前有效
          router.push('/list');
          return;
        }
        ElMessage({type:'warning', message});
       }).catch( reason => {
        if( reason instanceof Error ) {
            ElMessage.error('登录失败');
          }
       })
}

function change(name) {
  form.email = '';
  form.tel = '';
}
</script>

<template>
  <el-container>
    <el-header>
      <h3>用户登录</h3>
    </el-header>
    <el-main>
      <el-tabs type="border-card" @tab-change="change">
        <el-tab-pane label="邮箱">
          <el-form :model="form" label-width="120px">
            <el-form-item label="登录邮箱">
              <el-input v-model="form.email" />
            </el-form-item>
            <el-form-item label="登录密码">
              <el-input type="password" v-model="form.password" />
            </el-form-item>
            <el-form-item label="">
              <el-button type="primary" @click="login">登录</el-button>
            </el-form-item>
          </el-form>
        </el-tab-pane>
        <el-tab-pane label="手机号">
          <el-form :model="form" label-width="120px">
            <el-form-item label="手机号">
              <el-input v-model="form.tel"/>
            </el-form-item>
            <el-form-item label="登录密码">
              <el-input type="password" v-model="form.password" />
            </el-form-item>
            <el-form-item label="">
              <el-button type="primary" @click="login">登录</el-button>
            </el-form-item>
          </el-form>
        </el-tab-pane>
      </el-tabs>
    </el-main>
    <el-footer>
      没有账号？前去<a href="/register">注册</a>
    </el-footer>
  </el-container>
</template>

<style scoped>

</style>